<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;

class OssFile extends Model
{
    // 设置表名
    protected $name = 'oss_file';
    
    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 设置时间字段格式
    protected $dateFormat = 'Y-m-d H:i:s';
    
    // 设置时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 类型转换
    protected $type = [
        'id'          => 'integer',
        'file_size'   => 'integer',
        'related_id'  => 'integer',
        'uploader_id' => 'integer',
        'width'       => 'integer',
        'height'      => 'integer',
        'create_time' => 'datetime',
        'update_time' => 'datetime',
        'delete_time' => 'datetime',
    ];

    /**
     * 标签获取器
     * @param string $value
     * @return array
     */
    public function getTagsAttr($value): array
    {
        return $value ? explode(',', $value) : [];
    }

    /**
     * 标���修改器
     * @param array|string $value
     * @return string
     */
    public function setTagsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : (string)$value;
    }

    /**
     * 保存文件记录
     * @param array $fileData 文件数据
     * @param array $uploader 上传者信息
     * @param array $extend 扩展信息
     * @return bool
     */
    public static function saveFile(array $fileData, array $uploader, array $extend = []): bool
    {
        $data = [
            'file_name'     => $fileData['file_name'] ?? '',
            'file_path'     => $fileData['file_path'] ?? '',
            'file_url'      => $fileData['file_url'] ?? '',
            'file_size'     => $fileData['file_size'] ?? 0,
            'file_ext'      => $fileData['file_ext'] ?? '',
            'mime_type'     => $fileData['mime_type'] ?? '',
            'width'         => $fileData['width'] ?? null,
            'height'        => $fileData['height'] ?? null,
            'fingerprint'   => $fileData['fingerprint'] ?? null,
            'uploader_type' => $uploader['type'] ?? '',
            'uploader_id'   => $uploader['id'] ?? 0,
            'uploader_name' => $uploader['name'] ?? '',
            'upload_ip'     => $uploader['ip'] ?? request()->ip(),
            'module'        => $extend['module'] ?? '',
            'purpose'       => $extend['purpose'] ?? '',
            'remark'        => $extend['remark'] ?? '',
            'tags'          => $extend['tags'] ?? '',
            'related_id'    => $extend['related_id'] ?? 0,
        ];

        return self::create($data) !== false;
    }

    /**
     * 获取文件列表
     * @param array $params 查询参数
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public static function getList(array $params = [], int $page = 1, int $limit = 10): array
    {
        $query = self::whereNull('delete_time');

        // 按模块筛选
        if (!empty($params['module'])) {
            $query->where('module', $params['module']);
        }

        // 按用途筛选
        if (!empty($params['purpose'])) {
            $query->where('purpose', $params['purpose']);
        }

        // 按上传者筛选
        if (!empty($params['uploader_type'])) {
            $query->where('uploader_type', $params['uploader_type']);
        }
        if (!empty($params['uploader_id'])) {
            $query->where('uploader_id', $params['uploader_id']);
        }

        // 按文件类型筛选
        if (!empty($params['file_ext'])) {
            $query->where('file_ext', $params['file_ext']);
        }

        // 按关联ID筛选
        if (!empty($params['related_id'])) {
            $query->where('related_id', $params['related_id']);
        }

        // 按标签筛选
        if (!empty($params['tag'])) {
            $query->whereLike('tags', "%{$params['tag']}%");
        }

        // 按文件名搜索
        if (!empty($params['keyword'])) {
            $query->whereLike('file_name|remark', "%{$params['keyword']}%");
        }

        $total = $query->count();
        $list = $query->order('create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return [
            'total' => $total,
            'list' => $list,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取文件信息
     * @param int $fileId
     * @return array|null
     */
    public static function getInfo(int $fileId): ?array
    {
        $file = self::find($fileId);
        return $file ? $file->toArray() : null;
    }

    /**
     * 批量获取文件URL
     * @param array $fileIds
     * @return array
     */
    public static function getFileUrls(array $fileIds): array
    {
        if (empty($fileIds)) {
            return [];
        }

        return self::whereIn('id', $fileIds)
            ->whereNull('delete_time')
            ->column('file_url', 'id');
    }

    /**
     * 更新文件信息
     * @param int $fileId
     * @param array $data
     * @return bool
     */
    public static function updateFile(int $fileId, array $data): bool
    {
        $allowFields = [
            'module', 'purpose', 'remark', 'tags', 
            'related_id', 'width', 'height'
        ];
        
        $updateData = array_intersect_key($data, array_flip($allowFields));
        if (empty($updateData)) {
            return false;
        }

        return self::where('id', $fileId)->update($updateData) !== false;
    }

    /**
     * 删除文件记录
     * @param int|array $fileIds
     * @return bool
     */
    public static function deleteFile($fileIds): bool
    {
        return self::destroy($fileIds) !== false;
    }
}
